//
//  WelcomeSecondView.swift
//  ShouChong
//
//  Created by 陈友文 on 2024/6/13.
//

import SwiftUI
import ZLPhotoBrowser
import MMDrawerController

struct WelcomeSecondView: View {
    @AppStorage("curren_main_color") var currentMainColor = "color_main_01"
    @AppStorage("user_name") var userName = ""
    @AppStorage("user_avator") var userAvatar = "user_header_01"
    @AppStorage("user_age") var userAge = "60后"
    @AppStorage("user_sex") var userSex = "0"
    @AppStorage("user_avator_base64") var avatorBase64 = ""
    
    @State private var showDialog:Bool = false
    @State private var showAvatarView:Bool = false
    @State private var imageString:String = ""
    
    @ObservedObject var welcomeVM:WelcomeVM = WelcomeVM()
    @AppStorage("login_token") var loginToken:String = ""
    
    var confirmBlock:() -> Void
    
    var body: some View {
        VStack {
            
            Text("展示您的个性化")
                .modifier(MainTextModifier(fontSize: 28, fontWeight: .bold, foreColor: Color("color_text_black")))
                .padding(.top,40)
                .padding(.bottom,40)
            HStack {
                Text("设置您的头像")
                    .modifier(MainTextModifier(fontSize: 16, fontWeight: .bold, foreColor: Color("color_text_black")))
                Spacer()
            }
            .padding(.bottom,12)
            .padding(.horizontal,20)
            
            Image(uiImage: imageString.imageFromBase64 ?? UIImage(named: userAvatar)!)
                .resizable()
                .frame(width:100,height: 100)
                .aspectRatio(contentMode: .fill)
                .cornerRadius(50)
                .overlay(alignment: .bottomTrailing) {
                    Button(action: {
                        showDialog.toggle()
                    }, label: {
                        Image(systemName: "plus")
                            .foregroundColor(Color.white)
                    }).frame(width: 24,height: 24)
                        .background(Color(currentMainColor))
                        .cornerRadius(12)
                }
                .padding(.bottom,50)
            
            HStack {
                Text("输入您的名称")
                    .modifier(MainTextModifier(fontSize: 16, fontWeight: .bold, foreColor: Color("color_text_black")))
                Spacer()
            }
            .padding(.bottom,12)
            .padding(.horizontal,20)
            
            HStack {
                Image(systemName: "person.fill")
                    .resizable()
                    .foregroundColor(Color(currentMainColor))
                    .frame(width: 20,height:20)
                    .aspectRatio(contentMode: .fit)
                    .padding(.leading,10)
                TextField("", text: $userName)
                    .scaleEffect(/*@START_MENU_TOKEN@*/CGSize(width: 1.0, height: 1.0)/*@END_MENU_TOKEN@*/)
                Image(systemName: "dice.fill")
                    .resizable()
                    .foregroundColor(Color(currentMainColor))
                    .frame(width: 20,height: 20)
                    .aspectRatio(contentMode: .fit)
                    .padding(.trailing,10)
                    .onTapGesture {
                        let generator = UIImpactFeedbackGenerator(style: .light)
                        generator.prepare()
                        generator.impactOccurred()
                        randomUserName()
                    }
            }
                .frame(height: 56)
                .background(Color("color_white"))
                .cornerRadius(10)
                .padding(.horizontal,20)
            Spacer()
          
            ShakeButton(label: Text("完 成").modifier(MainButtonModifier(width: kScreenWidth - 50))
            ) {
                let sendData = [
                    "name":userName,
                    "age":userAge,
                    "uid":UUID().uuidString,
                    "vip":"0",
                    "image":imageString,
                    "sex":userSex
                ]
                registUserFirstIn(sendData: sendData)
            }
            
            
            Spacer()
        }
        .overlay(alignment: .topTrailing, content: {
            ShakeButton(label: Text("跳过").modifier(MainTextModifier(fontSize: 14, fontWeight: .medium, foreColor: Color("color_text_black")))) {
                userAvatar = "user_header_01"
                avatorBase64 = UIImage(named: "user_header_01")?.base64 ?? ""
                let randomName = RandomNameTool.getName()
                userName = randomName
                let sendData = [
                    "name":randomName,
                    "age":userAge,
                    "uid":UUID().uuidString,
                    "vip":"0",
                    "image":UIImage(named: "user_header_01")?.base64 ?? "",
                    "sex":userSex
                ]
                registUserFirstIn(sendData: sendData)
            }.offset(x:-20,y:10)
        })
        .actionSheet(isPresented: $showDialog, content: {
            ActionSheet(title: Text("选择头像"),buttons: [
                .default(Text("app自带头像"), action: {
                    showAvatarView.toggle()
                }),
                .default(Text("从系统相册选择"),action: {
                    selectPhotos()
                }),
                .cancel(Text("取消"))
                
            ])
        })
        .sheet(isPresented: $showAvatarView, onDismiss:{
            if !userAvatar.isEmpty {
                self.imageString = UIImage(named: userAvatar)?.base64 ?? ""
                self.avatorBase64 = UIImage(named: userAvatar)?.base64 ?? ""
            }
        }, content: {
            AvatarChooseView()
        })
        
        .onAppear{
            randomUserName()
        }
    }
    
    
    private func registUserFirstIn(sendData:[String:String]) {
       
        welcomeVM.firstRegist(sendData: sendData) { res in
            guard let token = res as? String else {
                YWToast.show(text: "发生错误,请稍等")
                return
            }
            loginToken = token
//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//                let vc = BaseNavController(rootViewController: HomeViewController())
//                let settingVC = OpenNavViewController(rootViewController: SettingViewController())
//                let mmVC = MMDrawerController(center: vc, leftDrawerViewController:settingVC)
//                mmVC?.openDrawerGestureModeMask = .all
//                mmVC?.closeDrawerGestureModeMask = .all
//                mmVC?.showsShadow = true
//                mmVC?.maximumLeftDrawerWidth = 200
//                mmVC?.shadowRadius = 5
//                mmVC?.shadowColor = .gray.withAlphaComponent(0.4)
//                mmVC?.shouldStretchDrawer = false
//                UIApplication.shared.keyWindow?.rootViewController = mmVC
//            }
            confirmBlock()
        } failBlock: { error, code in
            YWToast.show(text: "发生错误,请稍等")
        }


    }

    
    
    private func randomUserName() {
        userName = RandomNameTool.getName()
    }
    
    
    private func selectPhotos() {
            let scene = UIApplication.shared.connectedScenes.first
            let root = (scene as? UIWindowScene)?.windows.first?.rootViewController
            if root != nil {
                ZLPhotoConfiguration.default().maxSelectCount = 1
                ZLPhotoConfiguration.default().allowEditVideo = false
                ZLPhotoConfiguration.default().allowSelectVideo = false
                ZLPhotoConfiguration.default().allowSelectVideo = false
                ZLPhotoConfiguration.default().allowSelectLivePhoto = false
                let ac = ZLPhotoPreviewSheet()
                ac.selectImageBlock = {  results,isOriginal in
                    let scaleImage = results.first?.image.scale(newWidth: 300)
                    guard let imageStr = scaleImage?.base64 else {
                        YWToast.show(text: "获取图片失败")
                        return
                    }
                    imageString = imageStr
                    avatorBase64 = imageStr
                }
                ac.showPhotoLibrary(sender: root!)
            }
        }
}

